package com.zhx.real.security.entry;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * describe:替换掉 默认跳转url 的401错误   此重写可以完全使得未登录的401变为json格式
 *
 * @author zhanghaixuan
 * @date 2018/06/29
 **/
@Slf4j
public class UnauthorizedEntryPoint implements AuthenticationEntryPoint {

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authException) throws IOException, ServletException {
		String requestURI = request.getRequestURI();

		log.error("当前401请求路径为:" + requestURI);

		response.setStatus(HttpStatus.UNAUTHORIZED.value());
		response.setContentType("application/json,charset=UTF-8");
		String message = "未登录,请登录!";
		response.getWriter().write("\"" + message + "\"");
	}
}
